package com.zwps.common.controller.shiro.filter;

import com.zwps.common.cache.CacheService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwps.common.controller.constant.HttpHeaderConstant;
import com.zwps.common.controller.response.message.ResponseMessage;
import com.zwps.common.controller.shiro.authc.JwtToken;
import com.zwps.common.core.exception.AbstractCommonException;
import com.zwps.common.core.exception.AuthenticationFailureException;

import cn.hutool.core.util.StrUtil;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 默认开启跨域设置（使用单体） 微服务情况下，此属性设置为false
     */
    private boolean allowOrigin = false;

    private CacheService cacheService;
    public JwtFilter() {
    }

    public JwtFilter(boolean allowOrigin, CacheService cacheService) {
        this.allowOrigin = allowOrigin;
        this.cacheService = cacheService;
    }

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            return executeLogin(request, response);
        } catch (AuthenticationException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof AbstractCommonException) {
                responseAuthenticationFailureMessage(response, cause.getMessage(), e);
            } else {
                responseAuthenticationFailureMessage(response, "Token校验失败", e);
            }
        } catch (AbstractCommonException e) {
            responseAuthenticationFailureMessage(response, e.getMessage(), e);
        } catch (Exception e) {
            responseAuthenticationFailureMessage(response, "登录已过期，请重新登录", e);
        }
        return false;
    }

    public void responseAuthenticationFailureMessage(ServletResponse response, String errorMsg, Exception e) {
        log.error("Authentication failure exception: ", e);
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        try (OutputStream os = httpServletResponse.getOutputStream();) {
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            os.write(new ObjectMapper().writeValueAsString(ResponseMessage.authenticationFailureMessage(errorMsg))
                    .getBytes("UTF-8"));
            os.flush();
        } catch (IOException e2) {
            log.error("Response write authentication failure exception: ", e2);
        }
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(HttpHeaderConstant.HEADER_TOKEAN);
        String casToken = httpServletRequest.getHeader(HttpHeaderConstant.HEADER_CAS_TOKEAN);

        if (StrUtil.isEmpty(token) && StrUtil.isEmpty(casToken)) {
            throw new AuthenticationFailureException("Token请求头不存在");
        }
        if(StrUtil.isNotEmpty(token)) {
            JwtToken jwtToken = new JwtToken(token);
            // 提交给realm进行登入，如果错误他会抛出异常并被捕获
            getSubject(request, response).login(jwtToken);
        } else {
            String value = cacheService.getValue(casToken);
            if(StrUtil.isEmpty(value)) {
                responseAuthenticationFailureMessage(response, "登录已过期，请重新登录", new Exception());
            }
        }

        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }


    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (allowOrigin) {
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    httpServletRequest.getHeader("Access-Control-Request-Headers"));
            // 是否允许发送Cookie，默认Cookie不包括在CORS请求之中。设为true时，表示服务器允许Cookie包含在请求中。
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        }
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
